package live.sidian.database.synchronizer.sync.structure.model;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.PropDesc;
import live.sidian.database.synchronizer.infrastructure.sql.SqlHelper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

/**
 * 记录连接数据库的配置信息
 */
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class Database {
    /**
     * 数据库主机地址
     */
    private String host;
    /**
     * 端口
     */
    private String port;

    /**
     * 登录用户
     */
    private String user;

    /**
     * 登录密码
     */
    private String password;

    /**
     * 字符编码
     */
    private String charset;

    /**
     * 库名
     */
    private String schema;

    /**
     * 信息是否完整可用. 字段全部必填
     */
    public boolean isReady() {
        for (PropDesc prop : BeanUtil.getBeanDesc(Database.class).getProps()) {
            Object value = prop.getValue(this);
            if (value == null) {
                return false;
            }
        }
        return true;
    }

    public SqlHelper toSqlHelper() {
        return toSqlHelper(false);
    }

    public SqlHelper toSqlHelper(boolean noSchema) {
        return new SqlHelper(
                String.format("jdbc:mysql://%s/%s?characterEncoding=%s&serverTimezone=GMT%%2B8",
                        host, noSchema ? "" : schema, charset),
                user, password
        );
    }

}
